//
//  JRefreshControl.swift
//  JMicroBlog
//
//  Created by Jason on 27/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit

class JRefreshControl: UIRefreshControl {
    /**
       storyboard开发 会先调用用init(coder aDecoder:NSCoder) 然后awakeFromNib()
       纯代码开发,只会调用init() / 如果是UIView 就调用init(frame:CGRect)
      */
    override init() {
        super.init()
        JLog.i("\(__FUNCTION__)",false)
        prepareView()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        prepareView()
    }
    
    var refreshView : JRefreshView?
    private func prepareView() {
        let rView = NSBundle.mainBundle().loadNibNamed("JRefreshView", owner: nil, options: nil).last as! JRefreshView
        // 添加子视图
        addSubview(rView)
        
        // 还是忘了关掉autoResizing
        rView.setTranslatesAutoresizingMaskIntoConstraints(false)
        // 设置约束
        // 一定要在自动布局前,先将子视图添加到视图中
        var cons = [AnyObject]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[rView(136)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView])
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rView(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView])
        cons.append(NSLayoutConstraint(item: rView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        
        self.addConstraints(cons)
        
        // 设置KVO观察者
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
        
        self.refreshView = rView
    }
    
    var showTipFlag = false
    var isLoadingFlag = false
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        JLog.i("\(self.frame)",false)
        if self.frame.origin.y > 0 {
            return
        }
        if refreshing && !isLoadingFlag{
            // 播放动画
            refreshView?.startLoading()
            isLoadingFlag = true
            return
        }
        if self.frame.origin.y < -50 && !showTipFlag{
            JLog.i("该翻转了",false)
            showTipFlag = true
            self.refreshView?.rotateTipIcon(showTipFlag)
        } else if self.frame.origin.y > -50 && showTipFlag {
            JLog.i("翻转回去",false)
            showTipFlag = false
            self.refreshView?.rotateTipIcon(showTipFlag)
        }
    }
    
    override func endRefreshing() {
        // 调用父类
        super.endRefreshing()
        // 停止动画
        refreshView?.stopLoading()
        // 重新设置动画标记
        isLoadingFlag = false
    }
    
    deinit {
        // KVO一定要被释放
        self.removeObserver(self, forKeyPath: "frame")
    }
}

class JRefreshView : UIView {
    
    // 箭头图标
    @IBOutlet weak var tipIconView: UIImageView!
    
    // 页面加载指示图标
    @IBOutlet weak var loadingView: UIImageView!
    // 提示视图
    @IBOutlet weak var tipView: UIView!
    // 旋转箭头
    func rotateTipIcon(clockWise:Bool) {
        var angle = CGFloat(M_PI)
        angle += clockWise ? -0.001 : 0.0001
        UIView.animateWithDuration(0.6, animations: {
           self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
        }) { _ in
            
        }
    }
    
    // 播放旋转动画
    func startLoading() {
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 1.0
        anim.repeatCount = MAXFLOAT
        loadingView.layer.addAnimation(anim, forKey: nil)
    }
    
    // 结束旋转动画
    func stopLoading() {
        // 删除加载动画
        loadingView.layer.removeAllAnimations()
        
        // 恢复箭头视图
        tipView.hidden = false
    }
}
